package com.qf.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.pojo.Course;
import com.qf.pojo.Subject;
import com.qf.service.CourseService;
import com.qf.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author 张鑫
 * @date 2020/10/20 14:12
 */
@Controller
@RequestMapping("course")
public class CourseController {

    @Autowired
    private CourseService courseService;
    @Autowired
    private SubjectService subjectService;

    // 展示课程信息
    @RequestMapping("showCourseList")
    public String showCourseList(Model model,
                                 @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                 @RequestParam(required = false, defaultValue = "10") Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        List<Course> courseList = courseService.findAll();
        PageInfo pageInfo = new PageInfo(courseList);
        model.addAttribute("page", pageInfo);
        return "/behind/courseList.jsp";
    }

    // 跳转添加课程信息
    @RequestMapping("addCourse")
    public String addCourse(Model model) {
        List<Subject> subjectList = subjectService.findAll();
        model.addAttribute("subjectList", subjectList);
        return "/behind/addCourse.jsp";
    }

    // 添加或修改课程信息
    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(Course course, Integer id) {
        if (id == null) {
            courseService.addCourse(course);
        } else {
            courseService.updateCourse(course);
        }
        return "redirect:/course/showCourseList";
    }

    // 编辑课程信息
    @RequestMapping("edit")
    public String edit(Integer id, Model model) {
        List<Subject> subjectList = subjectService.findAll();
        model.addAttribute("subjectList", subjectList);
        Course course = courseService.findById(id);
        model.addAttribute("course", course);
        return "/behind/addCourse.jsp";
    }

    // 删除课程信息
    @ResponseBody
    @RequestMapping("courseDel")
    public String courseDel(Integer id) {
        courseService.delCourse(id);
        return "success";
    }

    @RequestMapping("course/{id}")
    public String findSubjectById(@PathVariable(name = "id") Integer id, Model model) {

        Subject subject = subjectService.findSubjectById(id);
        model.addAttribute("subject", subject);


        List<Subject> subjectList = subjectService.findAll();
        model.addAttribute("subjectList", subjectList);

        return "/before/course.jsp";
    }


}
